﻿using System;

namespace PhiStore.Communication
{
    internal class ActivityMonitor
    {
        private long count;
        private static ActivityMonitor instance = null;
        private object mutex = new object();
        private DateTime lastZeroActivity;
        private long ActivityThreshold = 1000; //1 second
        //private long ActivityThreshold = 60000; //1 minute

        private ActivityMonitor()
        {
            count = 0;
            lastZeroActivity = DateTime.Now;
        }

        public static ActivityMonitor Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ActivityMonitor();
                }
                return instance;
            }
        }

        public void Reset()
        {
            lastZeroActivity = DateTime.Now;
        }

        public void IncreaseActivity()
        {
            lock (mutex)
            {
                count++;
            }
        }
        public void DecreaseActivity()
        {
            lock (mutex)
            {
                count--;
                if(count == 0)
                    lastZeroActivity = DateTime.Now;
            }
        }
        public bool HasActivity()
        {
            bool result = true;
            lock (mutex)
            {
                result = count > 0;
                long elapsed = (long) DateTime.Now.Subtract(lastZeroActivity).TotalMilliseconds;
                result |=  elapsed < ActivityThreshold;
            }
            return result;
        }


    }
}
